#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <signal.h>

void handle_sigchld(int sig) {
    // 处理SIGCHLD信号
    pid_t pid;
    int wstatus;
    while ((pid = waitpid(-1, &wstatus, WNOHANG)) > 0) {
        printf("Child with PID %d terminated\n", pid);
        if (WIFEXITED(wstatus)) {
            printf("exited, status=%d\n", WEXITSTATUS(wstatus));
        } else if (WIFSIGNALED(wstatus)) {
            printf("killed by signal %d\n", WTERMSIG(wstatus));
        } else if (WIFSTOPPED(wstatus)) {
            printf("stopped by signal %d\n", WSTOPSIG(wstatus));
        } else if (WIFCONTINUED(wstatus)) {
            printf("continued\n");
        }
    }
}

int main() {
    // 设置SIGCHLD的处理器
    struct sigaction sa;
    sa.sa_handler = handle_sigchld; // 设置信号处理函数
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART | SA_NOCLDSTOP; // 自动重启被信号打断的系统调用
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    // 创建子进程
    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    } else if (pid == 0) {
        // 子进程代码
        printf("This is the child process\n");
        exit(EXIT_SUCCESS);
    } else {
        // 父进程代码
        printf("This is the parent process\n");
        // 父进程可以继续执行其他任务
        // ...
        while (1) {
            usleep(1000000); // 父进程每隔1秒检查一次子进程状态
        }
    }

    return 0;
}